<template>
  <div>
    <el-dialog :title="title" width="800px" :visible.sync="visible" destroy-on-close @close="closeCallback">
      <div class="card">
      <p class="title"><i class="fa fa-th-large fa-lg"></i>鞋子信息</p>
      <el-form :model="shoeForm" status-icon :rules="rules" ref="shoeForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="类型" prop="stid">
          <el-select v-model="shoeForm.stid" placeholder="请选择类型" clearable filterable>
            <el-option v-for="item in types" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="品牌" prop="sbid">
          <el-select v-model="shoeForm.sbid" placeholder="请选择品牌" clearable filterable>
            <el-option v-for="item in brands" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="序列号" prop="snum">
          <el-input v-model="shoeForm.snum" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="sname">
          <el-input v-model="shoeForm.sname" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="sprices">
          <el-input-number v-model="shoeForm.sprices" :precision="2" :step="1.0" :min="0.0" :max="100000" autocomplete="off"></el-input-number>
        </el-form-item>
        <el-form-item label="折价" prop="sdiscount">
          <el-input-number v-model="shoeForm.sdiscount" :precision="2" :step="1.0" :min="0.0" :max="100000" autocomplete="off"></el-input-number>
        </el-form-item>
        <el-form-item label="上市时间" prop="spubtime">
          <el-date-picker v-model="shoeForm.spubtime" type="date" placeholder="选择上市日期" value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>
        <el-form-item label="产地" prop="sproducer">
          <el-input v-model="shoeForm.sproducer" autocomplete="off" clearable></el-input>
        </el-form-item>
        <el-form-item label="性别款式" prop="sgender">
          <el-radio-group v-model="shoeForm.sgender">
            <el-radio border label="男"></el-radio>
            <el-radio border label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="颜色" prop="scid">
          <el-select v-model="shoeForm.scid" placeholder="请选择颜色" clearable filterable>
            <el-option v-for="item in colors" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品描述" porp="sinfo">
          <el-input type="textarea" placeholder="请输入商品描述" v-model="shoeForm.sinfo" maxlength="20" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="累计销售量" prop="stimessold">
          <el-input-number v-model="shoeForm.stimessold" controls-position="right" :disabled="true"></el-input-number>
        </el-form-item>
        <el-form-item label="详细信息" porp="sdetail">
          <el-input type="textarea" placeholder="请输入详细信息" v-model="shoeForm.sdetail" maxlength="45" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="单品积分" prop="sintegral">
          <el-input-number v-model="shoeForm.sintegral" :precision="2" :step="1.0" :min="0.0" :max="100000" autocomplete="off"></el-input-number>
        </el-form-item>
        <el-form-item label="禁用状态" prop="sdelete">
          <el-switch v-model="shoeForm.sdelete"></el-switch>
        </el-form-item>
        <el-form-item label="尺码选择" prop="sizes">
          <el-checkbox-group v-model="shoeForm.sizes" size="mini">
            <el-checkbox-button
              v-for="(item,index) in sizes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
              :checked="item.sstateShow"
              @change="changeChecked(index)">
              <el-tag size="medium">{{ item.label }}码</el-tag>
              库存:
              <el-input-number v-model="item.scount" controls-position="right"></el-input-number>
              <el-switch v-if="item.sstateShow" v-model="item.sstate" active-color="#13ce66"></el-switch>
            </el-checkbox-button>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="产品图片" prop="spurl">
          <el-upload
            class="upload-demo"
            action=""
            ref="uploadFile"
            :file-list="fileList"
            :on-remove="handleRemove"
            :before-upload="beforeAvatarUpload"
            :on-preview="handlePictureCardPreview"
            :http-request="uploadFileMethod"
            list-type="picture-card"
            multiple>
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('shoeForm')">确 定</el-button>
          <el-button @click="resetForm('shoeForm')">重 置</el-button>
        </el-form-item>
      </el-form>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="imageVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import types from "../../../api/apis/product/types"
import brands from "../../../api/apis/product/brands"
import color from "../../../api/apis/product/color"
import size from "../../../api/apis/product/sizes"
import form from "../../../api/apis/product/shoes"
import execute from "../../../utils/constant/execute"
import stateCode from "../../../utils/constant/stateCode"
import baseConfig from "../../../utils/constant/baseConfig"

export default {
  name: "shoesInfo",
  props: {
    title: { type: String, default: "鞋子信息" },
    dialogVisible: { type: Boolean, default: false },
    shoes: {}
  },
  data () {
    var checkShoes = (rule, value, callback) => {
      if (this.oldName !== value) {
        form.fetchCheckShoes(value).then((res) => {
          if (res.data.code === stateCode.OPRATION_FAILED) {
            callback(new Error(res.data.msg))
          } else if (res.data.code === stateCode.OPRATION_SUCCESS) {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    var checkSnum = (rule, value, callback) => {
      if (this.oldSnum !== value) {
        form.fetchCheckSnum(value).then((res) => {
          if (res.data.code === stateCode.OPRATION_FAILED) {
            callback(new Error(res.data.msg))
          } else if (res.data.code === stateCode.OPRATION_SUCCESS) {
            callback()
          }
        })
      } else {
        callback()
      }
    }
    var validatorFigure = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error("金额不能小于0"))
      } else {
        callback()
      }
    }
    var checkPrice = (rule, value, callback) => {
      if (value > this.shoeForm.sprices) {
        callback(new Error("折价不能大于现价"))
      } else {
        callback()
      }
    }
    return {
      types: [],
      brands: [],
      colors: [],
      sizes: [],
      roleName: false,
      roleData: "",
      visible: this.dialogVisible,
      shoeForm: {sprices: 0, sdiscount: 0, sintegral: 0, sizes: []},
      oldName: "",
      oldSnum: "",
      fileList: [],
      dialogImageUrl: "",
      imageVisible: false,
      rules: {
        stid: [
          { required: true, message: "请选择类型", trigger: "change" }
        ],
        sbid: [
          { required: true, message: "请选择品牌", trigger: "change" }
        ],
        snum: [
          { required: true, message: "请输入序列号", trigger: "blur" },
          { pattern: /^[1-9][0-9]*$/, message: "请按照正确格式输入序列号", trigger: "blur" },
          { validator: checkSnum, trigger: ["blur", "change"] }
        ],
        sname: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 2, max: 18, message: "长度在 2 到 18 个字符", trigger: "blur" },
          { validator: checkShoes, trigger: ["blur", "change"] }
        ],
        sprices: [
          { required: true, message: "请输入现价", trigger: "blur" },
          { validator: validatorFigure, trigger: ["blur", "change"] }
        ],
        sdiscount: [
          { required: true, message: "请输入折价", trigger: "blur" },
          { validator: validatorFigure, trigger: ["blur", "change"] },
          { validator: checkPrice, trigger: ["blur", "change"] }
        ],
        spubtime: [
          { required: true, message: "请选择上市时间", trigger: "blur" }
        ],
        sproducer: [
          { required: true, message: "请填写产地", trigger: "blur" }
        ],
        sgender: [
          { required: true, message: "请选择性别款式", trigger: "blur" }
        ],
        scid: [
          { required: true, message: "请选择品牌", trigger: "change" }
        ]
      }
    }
  },
  methods: {
    closeCallback () {
      this.$emit("successCallback")
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === "image/jpeg"
      const isPNG = file.type === "image/png"
      const isLt500K = file.size / 1024 < 500

      let flag = true
      if (!(isJPG || isPNG)) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!")
        flag = false
      }
      if (!isLt500K) {
        this.$message.error("上传头像图片大小不能超过 500KB!")
        flag = false
      }
      return flag
    },
    uploadFileMethod (fileObj) {
      let spurlData = new FormData()
      let file = fileObj.file
      let fileName = file.uid + file.name.substring(file.name.lastIndexOf(".")).toLowerCase()
      spurlData.append("spurl", file, fileName)

      let uid = file.uid // 关键作用代码，去除文件列表失败文件
      let idx = this.$refs.uploadFile.uploadFiles.findIndex(item => item.uid === uid) // 关键作用代码，去除文件列表失败文件（uploadFiles为el-upload中的ref值）

      form.fetchUploadPhoto(spurlData).then((res) => {
        if (res.data.code === stateCode.OPRATION_SUCCESS) {
          this.$message({ type: execute.SUCCESS, message: res.data.msg })
          this.fileList.push({spid: -1, url: baseConfig.baseUrl + "image/" + fileName, name: fileName, spurl: fileName, uid: uid})
        } else {
          this.$message({ type: execute.WARNING, message: res.data.msg })
          this.$refs.uploadFile.uploadFiles.splice(idx, 1) // 关键作用代码，去除文件列表失败文件
        }
      }).catch((res) => {
        this.$message({
          showClose: true,
          message: res.data.msg,
          type: execute.ERROR
        })
        this.$refs.uploadFile.uploadFiles.splice(idx, 1) // 关键作用代码，去除文件列表失败文件
      })
    },
    handleRemove (file, fileList) {
      let fileName = file.uid + file.name.substring(file.name.lastIndexOf(".")).toLowerCase()
      let sid = this.shoeForm.sid === undefined ? -1 : this.shoeForm.sid
      form.fetchDeletePhoto(sid, fileName).then((res) => {
        if (res.data.code === stateCode.OPRATION_SUCCESS) {
          this.$message({ type: execute.SUCCESS, message: res.data.msg })
          let index = -1
          for (let i = 0; i < this.fileList.length; i++) {
            if (this.fileList[i].name === fileName) {
              index = i
              break
            }
          }
          if (index > -1) {
            this.fileList.splice(index, 1)
          }
        } else {
          this.$message({ type: execute.WARNING, message: res.data.msg })
          this.$refs.uploadFile.uploadFiles.push(file)
        }
      }).catch((res) => {
        this.$message({
          showClose: true,
          message: res.data.msg,
          type: execute.ERROR
        })
        this.$refs.uploadFile.uploadFiles.push(file)
      })
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.imageVisible = true
    },
    changeChecked (index) {
      this.sizes[index].sstateShow = !this.sizes[index].sstateShow
    },
    loadData () {
      types.fetchGetAllTypes().then((res) => {
        let typesList = []
        for (let data of res.data.data) {
          typesList.push({value: data.tid, label: data.tname, disabled: data.tdelete})
        }
        this.types = typesList
      })
      brands.fetchGetAllBrands().then((res) => {
        let brandsList = []
        for (let data of res.data.data) {
          brandsList.push({ value: data.bid, label: data.bname, disabled: data.bstate })
        }
        this.brands = brandsList
      })
      color.fetchGetAllColor().then((res) => {
        let colorList = []
        for (let data of res.data.data) {
          colorList.push({ value: data.cid, label: data.cname, disabled: data.cstate })
        }
        this.colors = colorList
      })
      size.fetchGetAllSizes().then((res) => {
        let sizesList = []
        for (let data of res.data.data) {
          sizesList.push({ ssid: -1, value: data.sizeid, label: data.sizenum, disabled: data.sstate, scount: 0, sstateShow: false, sstate: false })
        }
        this.sizes = sizesList
        if (this.title === "鞋子修改") {
          this.shoeForm = this.shoes
          this.shoeForm.sizes = []
          this.oldName = this.shoeForm.sname
          this.oldSnum = this.shoeForm.snum
          for (let index = 0; index < this.sizes.length; index++) {
            for (let checksState of this.shoeForm.shoeSizes) {
              if (checksState.s_sizeid === this.sizes[index].value) {
                this.sizes[index].ssid = checksState.ssid
                this.sizes[index].value = checksState.s_sizeid
                this.sizes[index].scount = checksState.scount
                this.sizes[index].disabled = false
                this.sizes[index].sstateShow = true
                this.sizes[index].sstate = checksState.sstate
              }
            }
          }
          let photoList = []
          for (let photos of this.shoeForm.shoePhotos) {
            photoList.push({spid: photos.spid, name: photos.spurl, url: baseConfig.baseUrl + "image/" + photos.spurl, uid: photos.spurl.substring(0, photos.spurl.lastIndexOf("."))})
          }
          this.fileList = photoList
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let sizesList = []
          for (let checkSizes of this.shoeForm.sizes) {
            for (let checkScount of this.sizes) {
              if (checkScount.label === checkSizes) {
                sizesList.push({ssid: checkScount.ssid, s_sizeid: checkScount.value, scount: checkScount.scount, sstate: checkScount.sstate})
              }
            }
          }
          let spurls = []
          for (let url of this.fileList) {
            spurls.push({spid: url.spid, spurl: url.name})
          }
          let formData = {
            sid: this.shoeForm.sid,
            snum: this.shoeForm.snum,
            sname: this.shoeForm.sname,
            sprices: this.shoeForm.sprices,
            sdiscount: this.shoeForm.sdiscount,
            spubtime: this.shoeForm.spubtime,
            sproducer: this.shoeForm.sproducer,
            sgender: this.shoeForm.sgender,
            sinfo: this.shoeForm.sinfo,
            stimessold: this.shoeForm.stimessold,
            sdetail: this.shoeForm.sdetail,
            sintegral: this.shoeForm.sintegral,
            sdelete: this.shoeForm.sdelete ? 1 : 0,
            sremarks: this.shoeForm.sremarks,
            stid: this.shoeForm.stid,
            sbid: this.shoeForm.sbid,
            scid: this.shoeForm.scid,
            shoeSizes: sizesList,
            shoePhotos: spurls
          }
          if (this.shoeForm.sid !== undefined) {
            form.fetchEditShoes(formData).then((res) => {
              if (res.data.code === stateCode.OPRATION_SUCCESS) {
                this.$message({ type: execute.SUCCESS, message: res.data.msg })
              } else {
                this.$message({ type: execute.WARNING, message: res.data.msg })
              }
            }).catch((res) => {
              this.$message({
                showClose: true,
                message: res.data.msg,
                type: execute.ERROR
              })
            })
          } else {
            form.fetchAddShoes(formData).then((res) => {
              if (res.data.code === stateCode.OPRATION_SUCCESS) {
                this.$message({ type: execute.SUCCESS, message: res.data.msg })
              } else {
                this.$message({ type: execute.WARNING, message: res.data.msg })
              }
            }).catch((res) => {
              this.$message({
                showClose: true,
                message: res.data.msg,
                type: execute.ERROR
              })
            })
          }
          this.visible = false
        } else {
          return false
        }
      })
      this.fileList = []
    }
  },
  mounted () {
    this.loadData()
  }
}
</script>
<style>
  .demo-ruleForm {
    width: 460px;
    padding-top: 25px;
  }
  .el-select {
    width: 100%;
  }
  .card {
    width: 560px;
    padding-bottom: 15px;
    margin: 0px auto;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .card .el-checkbox-button__inner{
    border-left: 1px solid #DCDFE6;
    border-radius: 4px 0 0 4px;
  }
</style>
